package com.asp.aspect;

import com.asp.constant.LoginCheckConstant;
import com.asp.constant.MessageConstant;
import com.asp.context.BaseContext;
import com.asp.exception.LoginStatusException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 自定义切面 用户登录检测
 * author:          ndg
 * date:            2024/1/8
 */
@Aspect
@Component
@Slf4j
public class LoginCheckAspect {

    @Pointcut("execution(* com.asp.service.*.*(..)) && @annotation(com.asp.annotation.LoginCheck)")
    public void LoginCheckPointCut() {
        //将相同的  切入点表达式抽取到 这
    }

    @Before("LoginCheckPointCut()")
    public void loginCheck(JoinPoint joinPoint) {
        log.info("用户登录检测");
        //log.info(new LoginStatusException(MessageConstant.LOGIN_STATUS).getMessage());

        //获得当前被拦截的方法的参数 -- 实体对象
        Object[] args = joinPoint.getArgs();

        // 没有参数 直接返回
        if (args == null || args.length == 0) {
            return;
        }
        String userName = null;
        Object entity = args[0];
        try {
            Method getUserName = entity.getClass().getDeclaredMethod(LoginCheckConstant.GET_USER_NAME);
            userName = (String) getUserName.invoke(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String loginUserName = BaseContext.getCurrentUserName();
        if (!Objects.equals(loginUserName, userName)) {
            throw new LoginStatusException(MessageConstant.LOGIN_STATUS);
        }
    }
}
